package com.quick;

import java.util.Arrays;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.quick.api.Result;
@RestControllerAdvice
@Slf4j
public class CommonResponseAdvice  implements ResponseBodyAdvice<Object>{
	private static final String[] exclude = {"ApiResourceController", "Swagger2ControllerWebMvc"};
	
	@Autowired ObjectMapper objectMapper;
	

	@Override
	public boolean supports(MethodParameter returnType, @SuppressWarnings("rawtypes") Class converterType) {
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			@SuppressWarnings("rawtypes") Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
		log.info("body:{}", body);
		if (Arrays.asList(exclude).contains(returnType.getDeclaringClass().getSimpleName())) {
            return body;
        }
		if (body instanceof String) {
            try {
                return new ObjectMapper().writeValueAsString(Result.ok(body));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
		if (body instanceof Result) {
	       return body;
	    }
		return Result.ok(body);
	}

}
